package com.example.controller;

import com.example.entity.Order;
import com.example.entity.User;
import com.example.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/order")
class OrderController {

    @Autowired
    private OrderService orderService;

    /**
     * 订单列表页（无论是否登录均可访问，未登录时显示空列表）
     */
    @GetMapping("/list")
    public String orderList(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user"); // 统一使用"user"键

        if (user == null) {
            return "redirect:/user/login";
        }

        List<Order> orders = orderService.getOrdersByUserId(user.getUserid());
        model.addAttribute("orders", orders);
        return "order";
    }

    /**
     * 取消订单（需登录）
     */
    @PostMapping("/cancel")
    @ResponseBody
    public String cancelOrder(@RequestParam Integer orderId, HttpSession session) {
        Integer userId = (Integer) session.getAttribute("userId");
        if (userId == null) {
            return "unauthorized";
        }
        return orderService.cancelOrder(orderId) ? "success" : "fail";
    }

    /**
     * 创建订单（需登录）
     */
    @PostMapping("/create")
    @ResponseBody
    public Map<String, Object> createOrder(@RequestParam String shopcartIds, HttpSession session) {
        Map<String, Object> response = new HashMap<>();
        User user = (User) session.getAttribute("user");

        if (user == null) {
            response.put("status", "unauthorized");
            return response;
        }

        try {
            Order order = orderService.createOrderFromCart(shopcartIds, user.getUserid());
            response.put("status", "success");
            // 统一使用小写orderid，与数据库字段一致
            response.put("orderid", order.getOrderid());  // 修改这里为小写
            return response;
        } catch (Exception e) {
            response.put("status", "fail");
            response.put("message", e.getMessage());
            return response;
        }
    }

    /**
     * 订单详情页
     */
    @GetMapping("/detail/{orderId}")
    public String orderDetail(@PathVariable("orderId") Integer orderId, HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/user/login";
        }

        Order order = orderService.getOrderById(orderId);
        if (order == null || !order.getUserid().equals(user.getUserid())) {
            return "redirect:/order/list";
        }

        model.addAttribute("order", order);
        return "orderDetail";
    }
    /**
     * Session调试接口（测试用）
     */
    @GetMapping("/testSession")
    @ResponseBody
    public String testSession(HttpSession session) {
        return "当前SessionID: " + session.getId()
                + ", 用户ID: " + session.getAttribute("userId");
    }

    @Controller
    @RequestMapping("/products")
    public class ProductController {

        @GetMapping
        public String listProducts(Model model) {
            // 添加业务逻辑
            return "product/list"; // 对应你的JSP文件路径
        }
    }
}
